from django.db import models


# Create your models here.

from django.db import models
from django.contrib.auth.models import AbstractUser
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from mall import settings
from django.conf import settings

# Create your models here.
class User(AbstractUser):
    """用户模型类"""
    mobile = models.CharField(max_length=11, unique=True, verbose_name='手机号')

    email_active = models.BooleanField(default=False, verbose_name='邮箱验证状态')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name



    def generice_active_url(self):

        serializer = Serializer(settings.SECRET_KEY, 3600)

        # 传递一个id就够了
        # 但是传递多个可以确保查询的准确性
        token = serializer.dumps({'id':self.id,'email':self.email})
        # token是bytes类型
        url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()

        return url

    @staticmethod
    def user_by_token(token):

        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            result = serializer.loads(token)
        except BadData:
            return None

        else:
            id = result.get('id')
            email = result.get('email')
            try:
                user = User.objects.filter(id=id, email=email)
            except User.DoesNotExist:
                return None
            else:
                return user